package com.hyk.commonLib.common.utils;

import androidx.annotation.Nullable;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Created by 贺玉琨 on 2019/9/3.
 */
public class AsyncUtils {
    @Nullable
    public static <T> T convertToSync(SyncRunnable<T> runnable) {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        AtomicReference<T> result = new AtomicReference<>();
        AppUtils.runOnUI(() -> {
            try {
                result.set(runnable.run());
            } catch (Exception ignored) {
            }
            countDownLatch.countDown();
        });
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            countDownLatch.countDown();
            e.printStackTrace();
        }
        return result.get();
    }


    public interface SyncRunnable<T> {
        T run() throws Exception;
    }
}
